import { Color, Vector3 } from 'three'
import Helper from '../../utils/Helper'
import Events from '../../application/constants/Events'
import { App } from '../../application'
import { Point } from '../../renderExtension/types/Point'
import Poi2 from './Poi2' // 导入Poi2类
import MeshUtil from '../../renderExtension/utils/MeshUtil'

/**
 * 圆形范围内的物体变色
 */
export default class CircleRange {
  private app: App
  private circleRangeData: {
    name: string
    nameColor: string
    nameLabelColor: string
    iconUrl: string
    circelCenter: Vector3
    circleRadius: number
    circleBorderWidth: number
    isOpenCircleRange: boolean
    circleRangeColor: Vector3
    circleBorderColor: Vector3
    circleRangeMix: number
    falldownSurface?
  }
  private refreshEvent
  private marker
  private circelCenterPoint: Point

  public constructor(param: {
    name: string
    nameColor: string
    nameLabelColor: string
    iconUrl: string
    circelCenter: Point
    circleRadius: number
    circleBorderWidth: number
    isOpenCircleRange: boolean
    circleRangeColor: string
    circleBorderColor: string
    circleRangeMix: number
    falldownSurface?
  }) {
    this.app = App.getInstance()
    this.circelCenterPoint = param.circelCenter.clone() // 保存原始的Point对象

    let circleRangeColor = new Color(param.circleRangeColor)
    let circleRangeColorVector = new Vector3(
      circleRangeColor.r,
      circleRangeColor.g,
      circleRangeColor.b
    )

    let circleBorderColor = new Color(param.circleBorderColor)
    let circleBorderColorVector = new Vector3(
      circleBorderColor.r,
      circleBorderColor.g,
      circleBorderColor.b
    )

    let circlePosition = param.circelCenter.clone().toEPSGWeb()
    // circlePosition = circlePosition.applyMatrix4(this.app.three.camera.matrixWorldInverse)
    this.circleRangeData = {
      name: param.name,
      nameColor: param.nameColor,
      nameLabelColor: param.nameLabelColor,
      iconUrl: param.iconUrl,
      circelCenter: new Vector3(circlePosition.x, circlePosition.y, 0),
      circleRadius: param.circleRadius,
      circleBorderWidth: param.circleBorderWidth,
      isOpenCircleRange: false,
      circleRangeColor: circleRangeColorVector,
      circleBorderColor: circleBorderColorVector,
      circleRangeMix: param.circleRangeMix,
      falldownSurface: param.falldownSurface
    };

    this.createCircle();
    this.createAirportMarker();
  }

  public openRange(){
      if(!this.circleRangeData || this.circleRangeData.isOpenCircleRange == true){
        return;
      }
      this.circleRangeData.isOpenCircleRange = true;
      this.updateSceneMaterial();
  }

  public closeRange(){
      if(!this.circleRangeData || this.circleRangeData.isOpenCircleRange == false){
        return;
      }
      this.circleRangeData.isOpenCircleRange = false;
      this.updateSceneMaterial();

      this.app.off(Events.AddTile, this.refreshEvent);
  }

  private createCircle() {
    this.updateSceneMaterial()

    this.refreshEvent = Helper.debounce2(
      this.updateSceneMaterial.bind(this),
      10,
      false
    )
    this.app.on(Events.AddTile, this.refreshEvent)
  }

  public dispose(){
    if(!this.circleRangeData){
      return;
    }

    MeshUtil.dispose(this.marker);
    this.circleRangeData.isOpenCircleRange = false;
    this.updateSceneMaterial();
    this.app.off(Events.AddTile, this.refreshEvent);
    this.circleRangeData = null;
  }

  private updateSceneMaterial() {
    let self = this
    Helper.traverseObject(this.app.three.scene, function (obj) {
      try {
        if (obj.type == 'Mesh') {
          if (obj.material.length > 1) {
            obj.material.forEach((element) => {
              if (element.material.setCircleRangeData) {
                element.material.setCircleRangeData(self.circleRangeData)
              }
            })
          } else {
            if (obj.material.setCircleRangeData) {
              obj.material.setCircleRangeData(self.circleRangeData)
            }
          }
        }
      } catch (error) {
        console.log(error)
      }

      return true
    })
  }

  /**
   * 创建机场标记（使用Poi2替代HtmlMarker）
   * @returns 返回创建的标记
   */
  private createAirportMarker() {
    // 使用Poi2创建机场标记
    const poi = new Poi2({
      position: this.circelCenterPoint,
      name: this.circleRangeData.name,
      size: 200, // 字体大小
      baseImageSize: 400, // 图标大小
      showText: true,
      textStyle: this.circleRangeData.nameColor, // 文字颜色
      strokeStyle: '#000000', // 文字描边颜色
      strokeWidth: 3, // 文字描边宽度
      isBold: true, // 文字加粗
      textPosition: 'top', // 文字位置在图标下方
      center: [0.5, 0.0], // 锚点设置
      depthTest: true,
      defaultShape: 'square', // 默认形状
      shapeSize: 2.0, // 形状大小
      // shapeColor: '#FFFFFF' // 形状颜色
      falldownSurface: this.circleRangeData.falldownSurface
    });

    // 设置背景色
    poi.updateTextBackground({
      enabled: true,
      color: this.hexToRgb(this.circleRangeData.nameLabelColor), // 转换颜色格式
      opacity: 0.9
    })

    // 调整文字位置，向上偏移一些距离
    poi.updateTextOffset({
      textOffsetY: 20 // 负值表示向上偏移
    })

    // 加载图标纹理
    if (this.circleRangeData.iconUrl) {
      console.log('this.circleRangeData.iconUrl', this.circleRangeData.iconUrl)
      // 直接传入URL字符串，不需要手动加载图片
      poi.updateShapeTexture(this.circleRangeData.iconUrl)
    }

    // 保存引用并添加到场景
    this.marker = poi
    this.app.add(this.marker)

    return this.marker
  }

  /**
   * 将十六进制颜色转换为RGB格式
   * @param hex 十六进制颜色字符串
   * @returns RGB格式字符串
   */
  private hexToRgb(hex: string): string {
    // 移除可能的#前缀
    hex = hex.replace(/^#/, '')

    // 处理简写形式，如#ABC转为#AABBCC
    if (hex.length === 3) {
      hex = hex
        .split('')
        .map((c) => c + c)
        .join('')
    }

    // 解析RGB值
    const r = parseInt(hex.substring(0, 2), 16)
    const g = parseInt(hex.substring(2, 4), 16)
    const b = parseInt(hex.substring(4, 6), 16)

    return `${r}, ${g}, ${b}`
  }

  /**
   * 移除机场标记点
   */
  public removeAirportMarker() {
    if (this.marker) {
      this.app.remove(this.marker)
      this.marker = null
    }
  }
}
